package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.api.domain.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-03
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteSkuStockService remoteSkuStockService;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 下单
     *
     * @return 结算商品信息
     */
    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityUtils.getUserId();
        R<List<CartInfo>> cartInfoListResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (R.FAIL == cartInfoListResult.getCode()) {
            throw new ServiceException(cartInfoListResult.getMsg());
        }
        List<CartInfo> cartInfoList = cartInfoListResult.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车没有选中商品");
        }


        // 封装订单信息
        List<OrderItem> orderItemList = null;
        BigDecimal totalAmount = new BigDecimal(0);
        if (!CollectionUtils.isEmpty(cartInfoList)) {
            orderItemList = cartInfoList.stream().map(cartInfo -> {
                OrderItem orderItem = new OrderItem();
                BeanUtils.copyProperties(cartInfo, orderItem);
                orderItem.setSkuNum(cartInfo.getSkuNum());
                return orderItem;
            }).collect(Collectors.toList());
        }
        // 计算总金额
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        //渲染订单确认界面-生成订单流水号(防止页面重复提交和页面等待超时)
        String tradeNo = generateTradeNo(userId);
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setIsBuy(false);

        return tradeVo;
    }

    /**
     * 提交订单
     *
     * @param orderForm 订单表单信息
     * @return orderId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityUtils.getUserId();
        // 1.防止重复提交订单和页面等待超时
        //判断订单号是否存在：

        /* 存在原子性问题
        Long userId = SecurityUtils.getUserId();
        * if(!this.checkTradeNo(userId.toString(), orderForm.getTradeNo())){
            throw new ServiceException("请勿重复提交订单");
        }
        //删除redis中的订单号
        this.deleteTradeNo(userId.toString());*/

        // 如果存在则说明用户第一次提交此订单
        // 如果五分钟内提交了第二次订单，则订单号不存在，则说明用户已经提交过该订单，不能重复提交
        // 如果五分钟之后第一次提交，则订单号也不存在，说明操作超时
        String userTradeKey = "user:tradeNo:" + userId;
        // 将键的值更为 processed  表示已处理
        // return 1 表示处理成功
        // return -1  键存在但值不匹配，表示重复提交
        // return 0   键不存在，订单过期
        String scriptText = """
                if redis.call('get', KEYS[1]) == ARGV[1] then
                       redis.call('set', KEYS[1], 'processed', 'ex', ARGV[2])
                       return 1
                   else
                   	if redis.call('exists', KEYS[1]) == 1 then
                           return -1
                       else
                       	return 0
                       end
                   end
                """;
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo(),300);
        if (flag == 0) {
            throw new ServiceException("操作超时，请退回重试");
        }
        if (flag == -1) {
            throw new ServiceException("请勿重复提交订单");
        }
        // 2.判断价格是否发生变化 并改变购物车中的价格
        //2.1 批量获取商品价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPriceVo>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();
        //2.2 遍历购物车商品 判断价格是否发生变化
        // TODO 在遍历购物车时 判断对应价格商品是否变化 传统写法需要循环嵌套 因此可以将sku商品的id和价格封装到map中
        String priceCheckResult = "";
        Map<Long, BigDecimal> skuPriceMap = skuPriceVoList
                .stream()
                .collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuPriceMap.get(orderItem.getSkuId())) != 0) {
                priceCheckResult += orderItem.getSkuName() + "\n";// 拼接商品名称 方便用户端提示
            }
        }
        //2.3 如果价格发生变化 则修改购物车价格
        if (StringUtils.hasText(priceCheckResult)) {
            R<Boolean> updateCartPriceResult = remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            if (R.FAIL == updateCartPriceResult.getCode()) {
                throw new ServiceException(updateCartPriceResult.getMsg());
            }
            throw new ServiceException("价格发生变化，请重新下单! \n" + priceCheckResult);
        }

        // 3.校验库存是否足够并锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();
        String checkAndLockResult = remoteSkuStockService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER).getData();
        if (StringUtils.hasText(checkAndLockResult)) {
            throw new ServiceException(checkAndLockResult);
        }

        // 4.下单
        Long orderId = null;
        try {
            //下单
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //下单失败，解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            //抛出异常
            throw new ServiceException("下单失败");
        }
        // 5.删除购物车选中商品
        if (!orderForm.getIsBuy()) {
            R<Boolean> deleteResult = remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
            if (R.FAIL == deleteResult.getCode()) {
                log.error(deleteResult.getMsg());
                //throw new ServiceException(deleteResult.getMsg());
            }
        }
        return orderId;
    }

    /**
     * 用户立即购买
     *
     * @param skuId
     * @return
     */
    @Override
    public TradeVo buy(Long skuId) {
        R<ProductSkuVo> productSkuVoResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuVoResult.getCode()) {
            throw new ServiceException(productSkuVoResult.getMsg());
        }
        ProductSkuVo productSkuVo = productSkuVoResult.getData();
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSkuVo.getSkuName());
        orderItem.setThumbImg(productSkuVo.getThumbImg());
        orderItem.setSkuPrice(productSkuVo.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(productSkuVo.getSalePrice());
        tradeVo.setIsBuy(true);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(generateTradeNo(SecurityUtils.getUserId()));

        return tradeVo;
    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityUtils.getUserId();

        System.out.println("orderStatus:" + orderStatus);

        List<OrderInfo> orderInfoList = baseMapper.selectList(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getUserId, userId)
                .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                .orderByDesc(OrderInfo::getCreateTime));// 根据创建时间倒序排序

        if (!CollectionUtils.isEmpty(orderInfoList)) {
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).collect(Collectors.toList());

            //查询orderItem
            List<OrderItem> orderItemList = orderItemMapper.selectList(
                    new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIdList)
            );
            Map<Long, List<OrderItem>> orderIdToOrderItemListMap = orderItemList.stream().collect(
                    Collectors.groupingBy(OrderItem::getOrderId)
            );

            //组装orderItemList
            orderInfoList.forEach(item -> {
                item.setOrderItemList(orderIdToOrderItemListMap.get(item.getId()));
            });
        }
        return orderInfoList;
    }

    @Override
    public OrderInfo selectOrderInfoById(Long orderId) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(orderId != null, OrderInfo::getId, orderId);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus() == 0) {//待付款
            orderInfo.setOrderStatus(-1);//已取消
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            baseMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);
            //发送MQ消息通知商品系统解锁库存：TODO
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        //订单
        OrderInfo orderInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo)
        );
        //订单详情
        List<OrderItem> orderItemList = orderItemMapper.selectList(
                new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId())
        );
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public void processPaySuccess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<OrderInfo>()
                        .eq(OrderInfo::getOrderNo, orderNo)
        );

        //幂等判断
        if(orderInfo.getOrderStatus() == 1){
            return;
        }
        orderInfo.setOrderStatus(1);
        orderInfo.setPaymentTime(new Date());
        baseMapper.updateById(orderInfo);
    }

    private Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        // 保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setOrderNo(orderForm.getTradeNo());//订单号
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //远程调用获取用户地址信息
        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(userId, SecurityConstants.INNER);
        if (R.FAIL == userAddressResult.getCode())
            throw new ServiceException(userAddressResult.getMsg());
        //获取用户地址信息
        UserAddress userAddress = userAddressResult.getData();
        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        //实时获取总价格
        //计算orderItem中商品的总价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = orderItemList
                .stream()
                .map(
                        orderItem -> orderItem.getSkuPrice()
                                .multiply(new BigDecimal(orderItem.getSkuNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //设置商品总价格
        orderInfo.setOriginalTotalAmount(totalAmount);//原价
        BigDecimal bigSale = new BigDecimal(0);
        orderInfo.setCouponAmount(bigSale);//优惠券减额
        orderInfo.setTotalAmount(totalAmount.subtract(bigSale));
        //订单状态
        orderInfo.setOrderStatus(0);//待付款

        orderInfo.setCreateBy(userName);
        orderInfo.setUpdateBy(userName);
        baseMapper.insert(orderInfo);
        // 保存订单项记录：order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateBy(userName);
            orderItem.setUpdateBy(userName);
            orderItemMapper.insert(orderItem);
        }
        // 保存订单日志记录：order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setOperateUser(userName);
        orderLog.setNote("提交订单");
        orderLog.setCreateBy(userName);
        orderLog.setUpdateBy(userName);
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 验证页面提交流水号是否有效
     * 当用户重复提交时，会先验证流水号是否相同，如果相同则返回true，否则返回false，并删除Redis中的流水号
     *
     * @param userId
     * @param tradeNo
     * @return
     */
    private Boolean checkTradeNo(String userId, String tradeNo) {
        String userTradeKey = "user:tradeNo:" + userId;
        String redisTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey);
        return tradeNo.equals(redisTradeNo);
    }

    /**
     * 删除流水号
     *
     * @param userId
     */
    private void deleteTradeNo(String userId) {
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }
}
